package com.sls.web.manager.action;

import java.net.URLDecoder;
import java.net.URLEncoder;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;
import org.springframework.beans.factory.annotation.Value;
import com.opensymphony.xwork2.ActionContext;
import com.sls.core.common.KeyUtil;
import com.sls.web.manager.common.Constants;
import com.sls.web.manager.pojo.UserInfoVO;
import com.sls.web.manager.sys.pojo.OperatorVO;
import com.sls.web.manager.sys.service.OperatorService;
import com.whalin.MemCached.MemCachedClient;

@InterceptorRefs(value = { @InterceptorRef("chainStack"),
		@InterceptorRef("rightsinterceptor"),
		@InterceptorRef("loginInterceptor") })
public class LoginAction extends SuperAction {
	/**
	 * 
	 */
	private static final long serialVersionUID = 2617796169933222153L;
	@Resource(name = "operatorService")
	private OperatorService operatorServie;
	private String captcha;
	private OperatorVO operator;
	@Resource(name = "memcachedClient")
	private MemCachedClient memCachedClient;
	@Value("${sso.login.passowrd}")
	private String ssoLoginPassword;
	private String errorRedirectionUrl;

	public OperatorVO getOperator() {
		return operator;
	}

	public String getCaptcha() {
		return captcha;
	}

	public String getErrorRedirectionUrl() {
		return errorRedirectionUrl;
	}

	public void setErrorRedirectionUrl(String errorRedirectionUrl) {
		this.errorRedirectionUrl = errorRedirectionUrl;
	}

	public void setCaptcha(String captcha) {
		this.captcha = captcha;
	}

	public void setOperator(OperatorVO operator) {
		this.operator = operator;
	}

	/**
	 * sso登录
	 * 
	 * @return
	 */
	public String ssoLogin() {
		if (StringUtils.isNotBlank(redirectionUrl)) {
			try {
				UserInfoVO str = this.getCurrentOperator();
				if (str.getUserId() == null || str.getUserName() == null
						|| str.getUserId().trim().length() == 0
						|| str.getUserName().trim().length() == 0)
					throw new NullPointerException();
				redirectionUrl = URLDecoder.decode(redirectionUrl, "utf-8");
				if (redirectionUrl.indexOf("/login!sso.htm") >= 0) {
					this.redirectionUrl = this.disploseSSO(this.redirectionUrl,
							str.getUserId(), str.getUserName(),
							ssoLoginPassword);
				}
				return "redirect";
			} catch (Exception e) {
			}
		}
		try {
			this.redirectionUrl = URLEncoder.encode(redirectionUrl, "utf-8");
		} catch (Exception e) {
		}
		return "redirectMain";
	}

	/**
	 * sso登录校验
	 * 
	 * @return
	 */
	public String ssoCheck() {
		UserInfoVO str = this.getCurrentOperator();
		if (str.getUserId() == null || str.getUserName() == null
				|| str.getUserId().trim().length() == 0
				|| str.getUserName().trim().length() == 0)
			this.redirectionUrl = this.errorRedirectionUrl;
		return "redirect";
	}

	/*
	 * 用户登陆
	 */
	public String login() {
		// 获取验证码
		Object randomCode = ActionContext.getContext().get(
				Constants.COOKIE_NAME_RANDOMCODE);
		this.setCaptcha(StringUtils.trim(this.getCaptcha()));
		if (randomCode == null
				|| (this.getCaptcha() == null)
				|| !this.getCaptcha().equalsIgnoreCase(
						KeyUtil.cookieCommonDencrypt(randomCode.toString()))) {
			ActionContext.getContext().put("login_error", "验证码错误,请重新输入!");
			try {
				this.redirectionUrl = URLEncoder
						.encode(redirectionUrl, "utf-8");
			} catch (Exception e) {
			}
			return this.index();
		}
		OperatorVO str;
		try {
			str = operatorServie.login(operator, this.getCurrentOperator()
					.getCurrentIp());
			ActionContext.getContext().put(Constants.COOKIE_NAME_USERINFO, str);
			if (StringUtils.isNotBlank(redirectionUrl)) {
				this.redirectionUrl = this.disploseSSO(this.redirectionUrl,
						str.getId(), str.getAccount(), ssoLoginPassword);
				return "redirect";
			} else
				return "redirectMain";
		} catch (Exception e) {
			try {
				if (StringUtils.isNotBlank(redirectionUrl))
					this.redirectionUrl = URLEncoder.encode(redirectionUrl,
							"utf-8");
			} catch (Exception es) {
			}
			ActionContext.getContext().put("login_error", e.getMessage());
			log.error("登录失败！");
		}
		return this.index();
	}

	// 后台Header
	public String header() {
		return "header";
	}

	// 后台首页
	public String index() {
		return "index";
	}

	// 列表
	public String list() {

		return "list";
	}

	/**
	 * 处理登录信息
	 * 
	 * @param redirectionUrl
	 * @param userId
	 * @param userName
	 * @param ssoLoginPassword
	 * @return
	 */
	private String disploseSSO(String redirectionUrl, String userId,
			String userName, String ssoLoginPassword) {
		if (redirectionUrl.indexOf("/login!sso.htm") >= 0) {
			try {
				StringBuilder sb = new StringBuilder();
				sb.append(userId.toString()).append(";")
						.append(userName.toString()).append(";");
				String sign = URLEncoder.encode(KeyUtil.commonHEXEncode(
						sb.toString(), ssoLoginPassword), "utf-8");
				if (redirectionUrl.indexOf("?") > 0) {
					redirectionUrl += "&sign=" + sign;
				} else {
					redirectionUrl += "?sign=" + sign;
				}
			} catch (Exception e) {
			}
		}
		return redirectionUrl;
	}

	public String main() {
		return "main";
	}

}